package cn.chenxing.module.file.controller;

import cn.chenxing.domain.dto.TrackData;
import cn.chenxing.domain.dto.TrackLine;
import cn.chenxing.domain.dto.TrackPoint;
import cn.chenxing.utils.TableUtil;
import cn.chenxing.domain.threadlocal.ThreadData;
import cn.chenxing.domain.threadlocal.ThreadLocalInfo;
import cn.chenxing.domain.util.DateUtil;
import cn.chenxing.domain.util.DialogBuilderUtil;
import cn.chenxing.domain.util.UsualExceptionUtil;
import cn.chenxing.module.file.service.FileService;
import cn.chenxing.utils.SftpUtil;
import com.jfoenix.controls.JFXComboBox;
import de.felixroske.jfxsupport.FXMLController;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @Description
 * @Author maogen.ymg
 * @Date 2020/3/20 22:44
 */
@Lazy
@FXMLController
@Slf4j
public class OnlineDataController implements Initializable {

    @FXML
    private JFXComboBox<String> fileList;

    @FXML
    private AnchorPane anchorPane;

    @FXML
    private BorderPane borderPane;

    @Autowired
    private FileService fileService;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        anchorPane.setVisible(false);
        ThreadLocalInfo.get().setOnlineDataPane(anchorPane);
        // 文件列表
        List<String> fileNameList =fileService.getUserFileNameList();
        if(!fileNameList.isEmpty()) {
            fileList.getItems().addAll(fileNameList);
            fileList.setValue(fileList.getItems().get(0));
        }

        if(ThreadData.get().getTrackTableList() != null) {
            TableUtil.importTableView(borderPane, null, true);
        }

    }

    @FXML
    private void backHomePage() {
        ThreadLocalInfo.get().getOnlineDataPane().setVisible(false);
        ThreadLocalInfo.get().getLocalDataPane().setVisible(false);
        ThreadLocalInfo.get().getFilePane().setVisible(true);
    }

    @FXML
    private void downLoad() {
        String fileUrl = fileList.getValue();
        DialogBuilderUtil.showPositiveAlert(StringUtils.isBlank(fileUrl), fileList,"注意", "选择的文件名为空");

        File tempFile;
        try {
            tempFile = SftpUtil.downloadToFile(fileUrl,"temp.txt");
        }catch (Exception e) {
            DialogBuilderUtil.showPositiveAlert(fileList,"提示", "文件下载失败");
            return;
        }

        if (tempFile==null || !tempFile.isFile()) {
            DialogBuilderUtil.showPositiveAlert(fileList,"提示", "文件下载失败");
            return;
        }

        List<TrackLine> trackLineList = new ArrayList<>();
        // 速度字段
        boolean hasSpeed = readData(tempFile, trackLineList);

        // 文件所有轨迹数据
        TrackData trackData = new TrackData();
        trackData.setTrackLineList(trackLineList);
        // 传值给ThreadData
        ThreadData.get().setFileUrl(fileUrl);
        ThreadData.get().setHasSpeed(hasSpeed);
        ThreadData.get().setTrackData(trackData);

        // 执行压缩算法，添加相关信息
        fileService.dpCompression();
        // 表格导入
        TableUtil.importTableView(borderPane, null, true);
    }

    @FXML
    private void updateList() {
        // 更新文件列表
        List<String> fileNameList =fileService.getUserFileNameList();
        fileList.getItems().clear();
        if(!fileNameList.isEmpty()) {
            fileList.getItems().addAll(fileNameList);
            fileList.setValue(fileList.getItems().get(0));
        }
        DialogBuilderUtil.showPositiveAlert(fileList,"提示", "文件列表更新成功");
    }

    @FXML
    private void dataInfo() {
        fileService.showDataInfo(fileList);
    }

    @FXML
    private void exportTable() {
        fileService.exportTable(fileList);
    }

    private boolean readData(File tempFile, List<TrackLine> trackLineList) {
        boolean hasSpeed = false;
        try(InputStreamReader inputReader = new InputStreamReader(new FileInputStream(tempFile));
            BufferedReader bReader = new BufferedReader(inputReader)) {

            // 首行
            String str = bReader.readLine();
            // 判断是否有速度字段
            String[] strGpsTemp = str.split(",");
            if(strGpsTemp.length > 4) {
                hasSpeed = true;
            }

            // 点ID
            int id = 0;
            // 用户ID
            int userId = -1;
            // 文件中ID数据
            int idValue = 0;
            // 是否是第一个ID
            boolean isFirstId = true;

            List<TrackPoint> primeCoordinate = new ArrayList<>();
            while ((str = bReader.readLine()) != null) {
                String[] strGps = str.split(",");
                // ID
                idValue = Integer.parseInt(strGps[0]);
                // 时间戳转换
                long timeStamp = DateUtil.date2TimeStamp(strGps[1], null);
                // 经度
                double longitude = Double.parseDouble(strGps[2]);
                // 纬度
                double latitude = Double.parseDouble(strGps[3]);

                TrackPoint point = new TrackPoint();
                point.setId(id++);
                point.setLongitude(longitude);
                point.setLatitude(latitude);
                point.setTimeStamp(timeStamp);
                // 速度字段
                if (hasSpeed) {
                    double speedField = Double.parseDouble(strGps[4]);
                    point.setSpeed(speedField);
                }

                // 第一个ID获取赋值给userId
                if (isFirstId) {
                    userId = idValue;
                    isFirstId = false;
                }
                if (idValue != userId) {
                    // List间赋值，而不是引用
                    List<TrackPoint> tempPointList = new ArrayList<>(primeCoordinate);
                    TrackLine trackLine = new TrackLine();
                    trackLine.setId(userId);
                    trackLine.setTrackPointList(tempPointList);
                    trackLineList.add(trackLine);
                    // 清空 为下一次服务
                    primeCoordinate.clear();
                    id = 0;
                    userId = idValue;
                } else {
                    primeCoordinate.add(point);
                }

            }// while
            TrackLine trackLine = new TrackLine();
            trackLine.setId(idValue);
            trackLine.setTrackPointList(primeCoordinate);
            trackLineList.add(trackLine);
        }catch (Exception e) {
            log.error("文件读取失败，原因为：{}", e.getLocalizedMessage(), e);
            DialogBuilderUtil.showPositiveAlert(fileList,"提示", "文件读取失败");
            // 删除临时文件
            if(tempFile.delete()) {
                log.info("临时文件删除成功");
            }
            UsualExceptionUtil.of("文件读取失败, 请查看原因");
        }

        // 删除临时文件
        if(tempFile.delete()) {
            log.info("临时文件删除成功");
        }
        if(trackLineList.isEmpty()) {
            DialogBuilderUtil.showPositiveAlert(fileList,"提示", "文件读取失败");
            UsualExceptionUtil.of("文件读取失败，请查看原因");
        }
        return hasSpeed;
    }
}
